<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  requestAnimationFrame()

  60Hz 1000/60 = 16.67ms 所以高于16.67ms刷新的动画是看不出效果的

  setInterval(function(){}, 17)也不能精准达到效果

  所以requestAnimationFrame()时间固定由系统给出

  <div id="test" style="width: 0px; height: 12px; line-height: 12px;background-color: red;">
    0%
  </div>

  <script>
    // 基本用法
    /* 
    var timer1 = requestAnimationFrame(function() {
      console.log(timer1);
    })

    var timer2 = requestAnimationFrame(function() {
      console.log(timer2);
    })

    var timer3 = requestAnimationFrame(function() {
      console.log(timer3);
    })

    cancelAnimationFrame(timer1)
 */

    // 兼容性写法
    /* 
    if(!window.requestAnimationFrame) {
      requestAnimationFrame = function(fn) {
        setTimeout(fn, 17)
      }
    }
 */

    // 进度条 练习题
    let test = document.getElementById('test')
    // setInterval
    // test.onclick = function() {
    //   let timer = setInterval(function fn() {
    //     if (parseInt(test.style.width) < 300) {
    //       test.style.width = parseInt(test.style.width) + 3 + 'px'
    //       test.innerHTML = parseInt(test.style.width) / 3 + '%'
    //     } else {
    //       clearInterval(timer)
    //     }
    //   }, 17)
    // }

    // setTimeout
    // test.onclick = function() {
    //   let timer = setTimeout(function fn() {
    //     if (parseInt(test.style.width) < 300) {
    //       test.style.width = parseInt(test.style.width) + 3 + 'px'
    //       test.innerHTML = parseInt(test.style.width) / 3 + '%'
    //       timer = setTimeout(fn, 17)
    //     } else {
    //       clearInterval(timer)
    //     }

    //   }, 17)
    // }

    // requestAnimationFrame()

    test.onclick = function () {
      let timer = requestAnimationFrame(function fn() {
        if (parseInt(test.style.width) < 300) {
          test.style.width = parseInt(test.style.width) + 3 + 'px'
          test.innerHTML = parseInt(test.style.width) / 3 + '%'
          timer = requestAnimationFrame(fn)
        } else {
          cancelAnimationFrame(timer)
        }

      })
    }
  </script>
</body>

</html>